//
//  HDNetworking.m
//  PortableTreasure
//
//  Created by HeDong on 16/2/10.
//  Copyright © 2016年 hedong. All rights reserved.
//

#import "HDNetworking.h"
#import "AFNetworking.h"
#import "HDPicModle.h"
#import "UIImage+HDExtension.h"
#import "LogInVC.h"
#import "CJAppInfo.h"
#import "CJDateTime.h"
//#import <AFNetworking/AFNetworking-umbrella.h>
@implementation HDNetworking
HDSingletonM(HDNetworking) // 单例实现
//static AFHTTPSessionManager *manager;
/**
 *  网络监测(在什么网络状态)
 *
 *  @param unknown          未知网络
 *  @param reachable        无网络
 *  @param reachableViaWWAN 蜂窝数据网
 *  @param reachableViaWiFi WiFi网络
 */
- (void)networkStatusUnknown:(Unknown)unknown reachable:(Reachable)reachable reachableViaWWAN:(ReachableViaWWAN)reachableViaWWAN reachableViaWiFi:(ReachableViaWiFi)reachableViaWiFi
{
    // 创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 监测到不同网络的情况
        NSLog(@"ddsfdsfdsfsdfs%ld",(long)status);
        switch (status)
        {
            case AFNetworkReachabilityStatusUnknown:
                unknown();
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                reachable();
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                reachableViaWWAN();
                
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                reachableViaWiFi();
                break;
                
            default:
                break;
        }
    }] ;
}



#pragma mark - 网络连接错误码处理
- (void)networkResponseErrorCodeDispose:(NSError * _Nonnull)error{
    
    //如果请求超时
    if (error.code == -1001) {
        [CJAlert showStringDismissWithDelay:@"请求超时，请检查网络！"];
                
    } else if (error.code == -1004) {
        
        [CJAlert showStringDismissWithDelay:@"无法连接服务器"];
        
    } else if (error.code == -1009) {
        
        [CJAlert showStringDismissWithDelay:CJStringWithFormat(@"您似乎断开了网络连接，请前往【设置】-【%@】-【无线数据】打开WLAN或者蜂窝网络",[CJAppInfo appName])];
        
    } else if (error.code == -1011) {
        
        [CJAlert showStringDismissWithDelay:@"服务器暂时不可用"];
        
    } else {
#ifdef DEBUG
        [CJAlert showStringDismissWithDelay:CJStringWithFormat(@"%ld", (long)error.code)];
#else
//        [CJAlert showStringDismissWithDelay:CJStringWithFormat(@"%@", error.localizedDescription)];
#endif
    }
}


/// 创建 AFHTTPSessionManager
- (AFHTTPSessionManager *)createSessionMangerWithHeader{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
    [contentTypes addObject:@"text/html"];
    [contentTypes addObject:@"text/plain"];
    [contentTypes addObject:@"application/json"];
    [contentTypes addObject:@"image/jpeg"];
    [contentTypes addObject:@"image/jpg"];
    [contentTypes addObject:@"application/octet-stream"];

    [manager.requestSerializer setValue:@"max-age=0" forHTTPHeaderField:@"Cache-Control"];
    [manager.requestSerializer setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3" forHTTPHeaderField:@"Accept-Language"];
    [manager.requestSerializer setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"binary" forHTTPHeaderField:@"Content-Encoding"];
    [manager.requestSerializer setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
    manager.responseSerializer.acceptableContentTypes = self.acceptableContentTypes;
    manager.requestSerializer.timeoutInterval = (self.timeoutInterval ? self.timeoutInterval : TIMEOUT);

    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 设置请求参数
    [manager.requestSerializer setValue:IsStrEmpty([self enTokenCode:CJFetchMyDefault(CJLogInResponseToken)]) ? @"":CJStringWithFormat(@"Bearer %@",[self enTokenCode:CJFetchMyDefault(CJLogInResponseToken)]) forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:[CJControl getDeviceUUID] forHTTPHeaderField:@"deviceId"];
    
    DLog(@"========  %@",CJFetchMyDefault(CJLogInResponseToken));
    return manager;
}


- (NSString *)enTokenCode:(NSString *)inputToken{
    
//    DLog(@"inputToken====    %@",inputToken);
//    DLog(@"获取当前时间戳s=== %ld",[CJDateTime getNowTimeSecondTamp]);
    NSString *strToken = CJStringWithFormat(@"%@%@",inputToken,[CJControl getHexByDecimal:[CJDateTime getNowTimeSecondTamp]]);
//    NSString *token = [self adjust:strToken];
//    NSString *token64 = [CJControl base64:token];
//    NSString *tokenBack = [self adjust:token64];
    return [self adjust:[CJControl base64:[self adjust:strToken]]];
  
}

- (NSString *)adjust:(NSString *)strToken{
    
    NSMutableArray *listToken = [self getTokenList:strToken];
    NSInteger listLength = listToken.count;
//    向下取整
    NSInteger middle = ceil(listLength/2);
    
    int asciiCodeFrist = [CJStringWithFormat(@"%@",listToken[0]) characterAtIndex:0];
    int asciiCodeEnd = [CJStringWithFormat(@"%@",listToken[listLength -1]) characterAtIndex:0];
    int start = (asciiCodeFrist + asciiCodeEnd)%3;
    
    for (int i = start; i < middle; i++) {
        
        if ([CJStringWithFormat(@"%@",listToken[i]) isEqualToString:CJStringWithFormat(@"%@",listToken[listLength -1 -i])]) {
            
        }else{
            //exchangeObjectAtIndex:需要交换的元素位置.
            //withObjectAtIndex:交换到哪个元素的位置.
            [listToken exchangeObjectAtIndex:i withObjectAtIndex:listLength -1 -i];
            int asciiCodeF = [CJStringWithFormat(@"%@",listToken[i]) characterAtIndex:0];
            int asciiCodeE = [CJStringWithFormat(@"%@",listToken[listLength -1 -i]) characterAtIndex:0];
            i+= (asciiCodeF + asciiCodeE)%2;
        }
    }
    
    return [listToken componentsJoinedByString:@""];
    
}


- (NSMutableArray *)getTokenList:(NSString *)strToken{
    
    NSMutableArray * arr = [NSMutableArray arrayWithCapacity:0];
        // 遍历字符串，按字符来遍历。每个字符将通过block参数中的substring传出
        [strToken enumerateSubstringsInRange:NSMakeRange(0, strToken.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
            [arr addObject:substring];
        }];
//    DLog(@"arr = %@", arr);
    return arr;
}


///展示登陆页
- (void)showLogInVCWindowWithMsg:(NSString *)msg{
    
    [CJControl clearAllUserDefaultsData];
    [[CJAlert shared]showStringTitle:msg nextStep:^(NSString *strSure) {
        LogInVC *vc = [[LogInVC alloc]init];
        UIViewController *viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        if ([viewController.presentedViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *navigation = (id)viewController.presentedViewController;
            if ([navigation.topViewController isKindOfClass:[LogInVC class]]) {
                return;
            }
        }

        if ([vc isKindOfClass:[UIViewController class]] == NO) return ;
        //              if (self.navigationController == nil) return ;
        
        if ([[CJControl getCurrentViewController] isKindOfClass:[LogInVC class]]) {
            return;
        }
        if (vc.hidesBottomBarWhenPushed == NO) {
            vc.hidesBottomBarWhenPushed = YES;
        }
        
        [[CJControl getCurrentViewController].navigationController pushViewController:vc animated:YES];
    }];

}

- (void)showMsgString:(NSString *)str{
    
    if (![str isEqualToString:@""]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [CJAlert showStringDismissWithDelay:str];
        });
    }
}



#pragma mark ---------- 延时加载提示
///  延时方法
- (void)delayMethod{
    [CJAlert showLoading];
}

- (void)setDelayCarryOut{
    [self performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:0.5];

}

- (void)cancleDelayCarryOut{
    
//    撤销所有延时执行
//    [NSObject cancelPreviousPerformRequestsWithTarget:self];
//    取消指定
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayMethod) object:nil];

}


/**
 *  封装的PUT请求
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param success    请求成功回调
 *  @param failure    请求失败回调
 */
- (void)PUT:(NSString *)URLString parameters:(id)parameters success:(Success)success failure:(Failure)failure{

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];

    @weakify(self);
    [[self createSessionMangerWithHeader] PUT:URLString parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        
            //  DLog(@"===== %@",responseObject);
//            DLog(@"======%@",[CJControl convertToJsonDataFromDic:responseObject]);

        NSString *status = [CJControl getThreeUnaryValueStr:responseObject[@"status"]];
        NSString *msg = [CJControl getThreeUnaryValueStr:responseObject[@"msg"]];
//        DLog(@"status============== %@",status);
        if (status.intValue == 0) {
            if (IsNilOrNull(responseObject[@"data"])) {
                success(@"");
            }else{
                success(responseObject[@"data"]);
            }

        }else if (status.intValue == 21332) {
            
            [self showLogInVCWindowWithMsg:msg];
        }else{
          [self showMsgString:msg];
        }

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        
        if (failure){
            failure(error);
        }
        [self networkResponseErrorCodeDispose:error];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
    
}


/// 电子签章用
/// @param URLString <#URLString description#>
/// @param parameters <#parameters description#>
/// @param success <#success description#>
/// @param failure <#failure description#>
- (void)PUTWithSign:(NSString *)URLString parameters:(id)parameters success:(Success)success failure:(Failure)failure{
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];
    
    @weakify(self);
    [[self createSessionMangerWithHeader] PUT:URLString parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        success(responseObject[@"data"]);
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        
        if (failure){
            failure(error);
        }
        [self networkResponseErrorCodeDispose:error];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
    
}


/**
 *  封装的DELETE请求
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param success    请求成功回调
 *  @param failure    请求失败回调
 */
- (void)DELETE:(NSString *)URLString parameters:(id )parameters success:(Success)success failure:(Failure)failure{
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];
    
    @weakify(self);
    [[self createSessionMangerWithHeader] DELETE:URLString parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
//        DLog(@"===== %@",responseObject);
//        DLog(@"======%@",[CJControl convertToJsonDataFromDic:responseObject]);

        NSString *status = [CJControl getThreeUnaryValueStr:responseObject[@"status"]];
        NSString *msg = [CJControl getThreeUnaryValueStr:responseObject[@"msg"]];

        if (status.intValue == 0) {
            success(responseObject[@"data"]);
        }else if (status.intValue == 21332) {
            
            [self showLogInVCWindowWithMsg:msg];
            
        }else{
          
            [self showMsgString:msg];
        }

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        if (failure){
            failure(error);
        }
        [self networkResponseErrorCodeDispose:error];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
}



/**
 *  封装的get请求
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param success    请求成功回调
 *  @param failure    请求失败回调
 */
- (void)GET:(NSString *)URLString parameters:(id )parameters success:(Success)success failure:(Failure)failure{

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];
    
    @weakify(self);
    [[self createSessionMangerWithHeader] GET:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        
//        DLog(@"======%@",[CJControl convertToJsonDataFromDic:responseObject]);
        NSString *status = [CJControl getThreeUnaryValueStr:responseObject[@"status"]];
        NSString *msg = [CJControl getThreeUnaryValueStr:responseObject[@"msg"]];

        if (status.intValue == 0) {
            
            success(responseObject[@"data"]);
            
        }else if (status.intValue == 21332) {

            [self showLogInVCWindowWithMsg:msg];
        }else{
            [self showMsgString:msg];
            NSError *error;
            if (failure){
                failure(error);
            }
        }
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        if (failure){
            failure(error);
        }
        [self networkResponseErrorCodeDispose:error];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
}

/**
 *  封装的POST请求
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param success    请求成功回调
 *  @param failure    请求失败回调
 */
- (void)POST:(NSString *)URLString parameters:(id)parameters success:(Success)success failure:(Failure)failure{
       
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];
    
    @weakify(self);
    [[self createSessionMangerWithHeader] POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        //            DLog(@"===== %@",responseObject);
        //            DLog(@"======%@",[CJControl convertToJsonDataFromDic:responseObject]);

        NSString *status = [CJControl getThreeUnaryValueStr:responseObject[@"status"]];
        NSString *msg = [CJControl getThreeUnaryValueStr:responseObject[@"msg"]];

        if (status.intValue == 0) {
            success(responseObject[@"data"]);
        }else if (status.intValue == 21332) {

            [self showLogInVCWindowWithMsg:msg];
        }else{

            [self showMsgString:msg];
        }

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        if (failure){
            failure(error);
        }
        [self networkResponseErrorCodeDispose:error];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
    
}

/**
 *  封装的POST请求 返回所有数据
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param success    请求成功回调
 *  @param failure    请求失败回调
 */
- (void)POSTReturnAllData:(NSString *)URLString parameters:(id)parameters success:(Success)success failure:(Failure)failure{

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];
    
    @weakify(self);
    [[self createSessionMangerWithHeader] POST:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        success(responseObject);
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        if (failure){
            failure(error);
        }
        [self networkResponseErrorCodeDispose:error];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
    
}

/**
 *  封装的get请求  没有提示信息
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param success    请求成功回调
 *  @param failure    请求失败回调
 */
- (void)GETWithNoMsgOnshow:(NSString *)URLString parameters:(id )parameters success:(Success)success failure:(Failure)failure{

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];
    
    @weakify(self);
    [[self createSessionMangerWithHeader] GET:URLString parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
//        DLog(@"======%@",[CJControl convertToJsonDataFromDic:responseObject]);

        NSString *status = [CJControl getThreeUnaryValueStr:responseObject[@"status"]];
        NSString *msg = [CJControl getThreeUnaryValueStr:responseObject[@"msg"]];
//        DLog(@"status============== %@",status);
        if (status.intValue == 0) {
            
            NSDictionary *dicS = (NSDictionary *)responseObject[@"data"];
            if (IsNilOrNull(dicS)) {
                
            }else{
                success(responseObject[@"data"]);
            }
          
        }else if (status.intValue == 21332) {
            
            [self showLogInVCWindowWithMsg:msg];
        }else{
            [self showMsgString:msg];
        }
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        if (failure){
            failure(error);
        }
        [self networkResponseErrorCodeDispose:error];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
}


/**
 *  封装POST图片上传(单张图片) // 可扩展成单个别的数据上传如:mp3等
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param picModle   上传的图片模型
 *  @param progress   进度的回调
 *  @param success    发送成功的回调
 *  @param failure    发送失败的回调
 */
- (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters andPic:(HDPicModle *)picModle progress:(Progress)progress success:(Success)success failure:(Failure)failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = self.acceptableContentTypes;
    manager.requestSerializer.timeoutInterval = (self.timeoutInterval ? self.timeoutInterval : 20);
    manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 请求不使用AFN默认转换,保持原有数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 响应不使用AFN默认转换,保持原有数据
    
    manager.requestSerializer.timeoutInterval = (self.timeoutInterval ? self.timeoutInterval : TIMEOUT);
        
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    // 设置请求参数
    [manager.requestSerializer setValue:IsStrEmpty([self enTokenCode:CJFetchMyDefault(CJLogInResponseToken)]) ? @"":CJStringWithFormat(@"Bearer %@",[self enTokenCode:CJFetchMyDefault(CJLogInResponseToken)]) forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:[CJControl getDeviceUUID] forHTTPHeaderField:@"deviceId"];
   
    [CJAlert showLoading];
    
    @weakify(self);
    [manager POST:URLString parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        /**
         *  压缩图片然后再上传(1.0代表无损 0~~1.0区间)
         */
        NSData *data = UIImageJPEGRepresentation(picModle.pic, 0.8); // 1.0
        CGFloat precent = self.picSize / (data.length / 1024.0);
        if (precent > 1)
        {
            precent = 1.0;
        }
        data = nil;
        data = UIImageJPEGRepresentation(picModle.pic, precent);
        
//        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", picModle.picName];
        
        [formData appendPartWithFileData:data name:picModle.picName fileName:picModle.fileName mimeType:@"image/jpeg"];
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (progress)
        {
            progress(uploadProgress); // HDLog(@"%lf", 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [CJAlert dismiss];
        if (success)
        {
            
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            success(dic);
            
            NSString *strStatus = [CJControl getThreeUnaryValueStr:dic[@"status"]];
            if (strStatus.intValue != 0) {
                [CJAlert showStringDismissWithDelay:[CJControl getThreeUnaryValueStr:dic[@"msg"]]];
            }
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        @strongify(self);
        if (failure){
            failure(error);
        }
        [CJAlert dismiss];
        [self networkResponseErrorCodeDispose:error];

    }];
    
}

#pragma mark ----------new-----


/// 网络请求 怎删改查
/// @param netType 请求方式
/// @param URLString URL
/// @param parameters <#parameters description#>
/// @param handleType <#handleType description#>
/// @param success <#success description#>
/// @param failure <#failure description#>
- (void)dataTaskWithHTTPMethod:(NetWorkType)netType url:(NSString *)URLString parameters:(id)parameters status:(DataHandleType)handleType success:(Success)success failure:(Failure)failure{
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];
    
    NSString *strNetType = @"";
    switch (netType) {
        case PostType:
            strNetType = @"POST";
            break;
        case DeleteType:
            strNetType = @"DELETE";
            break;
        case PutType:
            strNetType = @"PUT";
            break;
        case GetType:
            strNetType = @"GET";
            break;
        default:
            break;
    }
    
    @weakify(self);
    NSURLSessionDataTask *dataTask = [[self createSessionMangerWithHeader] dataTaskWithHTTPMethod:strNetType URLString:URLString parameters:parameters headers:nil uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];

        NSString *status = [CJControl getThreeUnaryValueStr:responseObject[@"status"]];
        NSString *msg = [CJControl getThreeUnaryValueStr:responseObject[@"msg"]];
        
//        登录失效
        if (status.intValue == 21332) {
            [self showLogInVCWindowWithMsg:msg];
            return;
        }
        
        if (handleType == ArpaDefault) {
            
            if (status.intValue == 0) {
                if (IsNilOrNull(responseObject[@"data"])) {
                    success(@"");
                }else{
                    success(responseObject[@"data"]);
                }
            }else{
              [self showMsgString:msg];
            }
        }else if (handleType == OperationTip){
            
            if (status.intValue == 0) {
                
                [[CJAlert shared]showStringTitle:msg nextStep:^(NSString *strSure) {
                    if (IsNilOrNull(responseObject[@"data"])) {
                        success(@"");
                    }else{
                        success(responseObject[@"data"]);
                    }
                }];
            }else{
              [self showMsgString:msg];
            }
    
        }else if (handleType == ReturnAllData){
            
            if (status.intValue == 0) {
                success(responseObject);
            }else{
              [self showMsgString:msg];
            }
            
        }

        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
        @strongify(self);
        [self cancleDelayCarryOut];
        [CJAlert dismiss];
        if (failure){
            failure(error);
        }
        [self networkResponseErrorCodeDispose:error];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }];
    
    [dataTask resume];
    
}


/// json传参
/// @param netType @”POST“ @”GET“ ...
/// @param urlString url
/// @param parameter 参数
/// @param handleType 状态
/// @param success 成功
/// @param failure 失败
- (void)jsonTaskWithHTTPMethod:(NetWorkType)netType urlString:(NSString * _Nonnull)urlString withParameter:(NSDictionary * _Nullable)parameter status:(DataHandleType)handleType  success:(Success)success failure:(Failure)failure {
   
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self setDelayCarryOut];
    
    NSString *strNetType = @"";
    switch (netType) {
        case PostType:
            strNetType = @"POST";
            break;
        case DeleteType:
            strNetType = @"DELETE";
            break;
        case PutType:
            strNetType = @"PUT";
            break;
        case GetType:
            strNetType = @"GET";
            break;
        default:
            break;
    }
    
   AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    @weakify(self);
   NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:strNetType URLString:urlString parameters:parameter error:nil];
   request.timeoutInterval = TIMEOUT;
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
   [request setValue:[CJControl getDeviceUUID] forHTTPHeaderField:@"deviceId"];
   [request setValue:IsStrEmpty([self enTokenCode:CJFetchMyDefault(CJLogInResponseToken)]) ? @"":CJStringWithFormat(@"Bearer %@",[self enTokenCode:CJFetchMyDefault(CJLogInResponseToken)]) forHTTPHeaderField:@"Authorization"];
    
   NSURLSessionDataTask *task = [manager dataTaskWithRequest:request
                                              uploadProgress:nil
                                            downloadProgress:nil
                                           completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
       @strongify(self);
       [self cancleDelayCarryOut];
       [CJAlert dismiss];

       if (!error) {
           
           NSString *status = [CJControl getThreeUnaryValueStr:responseObject[@"status"]];
           NSString *msg = [CJControl getThreeUnaryValueStr:responseObject[@"msg"]];
           
   //        登录失效
           if (status.intValue == 21332) {
               [self showLogInVCWindowWithMsg:msg];
               return;
           }
           
           if (handleType == ArpaDefault) {
               
               if (status.intValue == 0) {
                   if (IsNilOrNull(responseObject[@"data"])) {
                       success(@"");
                   }else{
                       success(responseObject[@"data"]);
                   }
               }else{
                 [self showMsgString:msg];
               }
           }else if (handleType == OperationTip){
               
               if (status.intValue == 0) {
                   
                   [[CJAlert shared]showStringTitle:msg nextStep:^(NSString *strSure) {
                       if (IsNilOrNull(responseObject[@"data"])) {
                           success(@"");
                       }else{
                           success(responseObject[@"data"]);
                       }
                   }];
               }else{
                 [self showMsgString:msg];
               }
       
           }else if (handleType == ReturnAllData){
               if (status.intValue == 0) {
                   success(responseObject);
               }else{
                 [self showMsgString:msg];
               }           }
           [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
           
       } else {
           
           [self cancleDelayCarryOut];
           [CJAlert dismiss];
           if (failure){
               failure(error);
           }
           [self networkResponseErrorCodeDispose:error];
           [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
       }
   }];
   
   [task resume];
}

@end



